from flask import session, render_template, current_app, jsonify, request, g

from info import constants
from info.models import User, News, Category, Comment, CommentLike
from . import news_blue
from info.utils.response_code import RET
from info.utils.commons import login_required
from info import db


# 首先利用装饰器获取用户的登陆状态
@news_blue.route('/')
@login_required
def index():
    user_id = session.get("user_id")
    user = None
    # 判断用户是不是已经登陆过，如果已经登陆，传入相应的数据
    if user_id:
        try:
            user = User.query.filter(User.id == user_id).first()
        except Exception as e:
            current_app.logger.error(e)
            # return jsonify(errno=RET.DBERR, errsmg="数据库错误")
    g.user = user
    # 传入排行榜的相关数据
    # 1首先查询数据库(数据库中已经有相应的数据)，将数据传入到data中
    # 2渲染数据
    list_object_news = None
    list_rank_news = []
    try:
        list_object_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if not list_object_news:
        current_app.logger.error(e)
        return jsonify(errno=RET.NODATA, errmsg="数据库没有数据")
    # for list_temp in list_object_news:
    for list_temp in list_object_news if list_object_news else []:
        # print(list_temp)
        list_rank_news.append(list_temp.to_dict())
    # print(list_rank_news)

    # 新闻列表的展示
    # 步骤： 1 查询分类数据库， 将data数据传入到index ，2渲染index页面
    list_category_all = None
    list_category = []
    try:
        list_category_all = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if not list_category_all:
        current_app.logger.error(e)
        return jsonify(errno=RET.NODATA, errmsg="数据库没有数据")
    for temp in list_category_all if list_category_all else None:
        list_category.append(temp.to_dict())

    # 新闻详情的产生（重新定义一个视图函数）
    data = {
        "user_info": user.to_dict() if user else None,
        "list_rank_news": list_rank_news,
        "list_category": list_category
    }
    # 1 查询语句查询所有的信息，按照时间排序，同时要分页处理 2 渲染数据至index
    return render_template("news/index.html", data=data)


@news_blue.route('/favicon.ico')
def favcion():
    return current_app.send_static_file("news/favicon.ico")


@news_blue.route('/news_list')
def get_news_list():
    """
    1 前段传入的数据为 cid page per_page
    2 根据参数，查询数据库，返回相应的数据给模板渲染
    老师的详细流程
    1 尝试获取参数，cid page per_page
    2 如果没有需要给默认值 例句request.args.get("cid",1)
    3 把页数和总页数强制转换为int
    4 根据分类id 查询数据库 按照新闻的发布时间进行排序， 使用paginate进行分页
    5 获取分页对象
    6 使用分页对象，获取分页后的新闻数据
      paginate = News.query.filter（News.category_id == cid）.order_by
      (News.create_time.desc()).paginate(page,per_page,False)
      news_data = paginate.items 总的新闻数据
      total_page = paginate.pages 总的页数
      current_page = paginate.page  当前页码
    7 遍历分页后的总页数，定义容器，调用to_dict()
    8 返回结果：总的页数， 当前页数 以及新的列表

    :return:
    """
    # 获取数据
    cid = request.args.get("cid", 1)  # 默认为1
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", 10)

    # 对页数和每页的条目进行强制转换
    try:
        page, per_page = int(page), int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="参数的格式有误")

    # 定义查询的过滤条件,如果cid=1 则要查询所有的数据，其他则查询相应的CID
    filters = []
    if cid != "1":
        filters.append(News.category_id == cid)

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻列表错误")

    news_list = paginate.items  # 新闻的所有数据
    total_page = paginate.pages  # 新闻总的页数
    current_page = paginate.page  # 新闻的当前的页码
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())

    data = {
        "new_dict_list": news_dict_list,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@news_blue.route('/<int:news_id>')
@login_required
def news_detail(news_id):
    comments = None
    is_collected = False
    # 1 加载新闻的详细信息
    try:
        news = News.query.get(news_id)
        # print(news)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="暂无数据")
    list_rank_news = []

    # 1 加载用户的评论信息
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
    comment_list = []
    for item in comments:
        comment_dict = item.to_dict()
        comment_list.append(comment_dict)

    # 2 加载排行的数据
    try:
        list_object_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if not list_object_news:
        return jsonify(errno=RET.NODATA, errmsg="数据库没有数据")
    # for list_temp in list_object_news:
    for list_temp in list_object_news if list_object_news else []:
        # print(list_temp)
        list_rank_news.append(list_temp.to_dict())
    # 3 加载收藏数据(用户不用登陆也可以查看相关的页面)
    try:
        g.user
    except Exception as e:
        g.user = None
        current_app.logger.error(e)
    else:
        if news in g.user.collection_news:
            is_collected = True
    news.clicks += 1
    data = {
        "news": news.to_dict(),
        'list_rank_news': list_rank_news,
        "is_collected": is_collected,
        "user_info": g.user.to_dict() if g.user else None,
        "comments": comment_list
    }
    # print(data["list_rank_news"])
    return render_template("news/detail.html", data=data)


# 收藏功能的实现
# 1 首先根据登陆的情况，判断是否能够收藏该数据
# 2 其次，判断新闻的id和是否已经收藏，然后操作数据库
@news_blue.route('/news_collect', methods=["POST"])
@login_required
def news_collect():
    user = g.user
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # print(news_id, action)

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="数据不完整")

    if action not in ["collect", "cancel_collect"]:
        jsonify(errno=RET.DATAERR, errsmg="数据错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="暂无数据")

    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据错误")
    return jsonify(errno=RET.OK, errmsg="OK")


@news_blue.route('/news_comment', methods=["POST"])
@login_required
def add_news_comment():
    try:
        user = g.user
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")
    else:
        if not user:
            return jsonify(errno=RET.NODATA, errmsg="用户未登陆")
    news_id = request.json.get("news_id")
    # print(news_id)
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    if not all([news_id, comment_str]):
        return jsonify(errno=RET.DATAERR, errmsg="数据不完整")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        print(news_id)
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")
    # 初始化数据库
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_str

    if parent_id:
        print(parent_id)
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存评论数据失败")
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())


@news_blue.route('/comment_like', methods=["POST"])
@login_required
def set_comment_like():
    """评论点赞"""

    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 获取参数
    comment_id = request.json.get("comment_id")
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 判断参数
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询评论数据
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")

    if action == "add":
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = g.user.id
            db.session.add(comment_like)
            # 增加点赞条数
            comment.like_count += 1
    else:
        # 删除点赞数据
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            # 减小点赞条数
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")
